package cn.dvptech.remotecontrol.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Path
import android.media.projection.MediaProjectionManager
import android.view.KeyEvent
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.recyclerview.widget.RecyclerView
import cn.dvptech.remotecontrol.R
import cn.dvptech.remotecontrol.app.TitleBarFragment
import cn.dvptech.remotecontrol.assists.Assists
import cn.dvptech.remotecontrol.screenmirror.configuration.VideoConfiguration
import cn.dvptech.remotecontrol.screenmirror.controller.StreamController
import cn.dvptech.remotecontrol.screenmirror.packer.Packer
import cn.dvptech.remotecontrol.screenmirror.packer.TcpPacker
import cn.dvptech.remotecontrol.screenmirror.screenHelper.Constant
import cn.dvptech.remotecontrol.screenmirror.sender.OnSenderListener
import cn.dvptech.remotecontrol.screenmirror.sender.Sender
import cn.dvptech.remotecontrol.screenmirror.sender.TcpSender
import cn.dvptech.remotecontrol.ui.activity.HomeActivity
import cn.dvptech.remotecontrol.ui.adapter.DeviceAdapter
import cn.dvptech.remotecontrol.ui.dialog.MessageDialog
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ThreadUtils
import com.hjq.base.BaseAdapter
import com.hjq.base.BaseDialog
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.widget.layout.WrapRecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber

/**
 *    author  : ulongx
 *    website : www.dvptech.cn
 *    date    : 2024/6/26
 *    desc    :
 */
class HomeFragment : TitleBarFragment<HomeActivity>(), OnRefreshLoadMoreListener, BaseAdapter.OnItemClickListener,
    OnSenderListener {
    override fun getLayoutId(): Int = R.layout.home_fragment

    private val refreshLayout: SmartRefreshLayout? by lazy { findViewById(R.id.rl_status_refresh) }
    private val recyclerView: WrapRecyclerView? by lazy { findViewById(R.id.rv_status_list) }
    private val closeCurrentConnect: View? by lazy { findViewById(R.id.close_current_connection_layout) }
    private val btnOpenFZService: AppCompatButton? by lazy { findViewById(R.id.open_fz_service) }

    private var adapter: DeviceAdapter? = null

    private var serverIP: String? = null
    // 投屏service
    private var mMediaProjectionManager: MediaProjectionManager? = null
    private var intentActivityResultLauncher: ActivityResultLauncher<Intent>? = null

    private var mStreamController: StreamController? = null
    private var mVideoConfiguration: VideoConfiguration? = null
    private var tcpSender: TcpSender? = null
    private var isRecord = false

    override fun initView() {

        setOnClickListener(closeCurrentConnect, btnOpenFZService)
        showSettingService()

        intentActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.data != null && result.resultCode == AppCompatActivity.RESULT_OK) {
//                showSettingService()
                // 投屏
//                val videoController = ScreenVideoVideoController(mMediaProjectionManager, result.resultCode, result.data)
//                mStreamController = StreamController(videoController)
                requestRecordSuccess()
            } else {
                toast("No data")
            }
        }

        adapter = DeviceAdapter(getAttachActivity()!!)
        adapter?.setOnItemClickListener(this)
        recyclerView?.adapter = adapter

        refreshLayout?.setOnRefreshLoadMoreListener(this)
    }

    fun startScreenCapture() {
        mMediaProjectionManager = getAttachActivity()?.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        intentActivityResultLauncher!!.launch(mMediaProjectionManager!!.createScreenCaptureIntent())
    }


    override fun initData() {

    }

    override fun onClick(view: View) {
        when(view){
            btnOpenFZService -> {
                Timber.d("open service")
//                clientSocketHelper?.sendMessage("btnOpenFZService test")
                if (!Assists.isAccessibilityServiceEnabled()) {
                    Assists.openAccessibilitySetting()
                } else {
                    // 已开启服务
                    toast(R.string.wifi_p2p_opened_assists_service)
                }
            }

            closeCurrentConnect -> {
                Timber.d("click closeCurrentConnect")
                MessageDialog.Builder(getAttachActivity()!!)
                    .setTitle("关闭提示")
                    .setMessage("确定要关闭连接吗？")
                    .setConfirm(getString(R.string.common_confirm))
                    .setCancel(getString(R.string.common_cancel))
                    .setListener(object : MessageDialog.OnListener {
                        override fun onConfirm(dialog: BaseDialog?) {
                            stopRecording()
                        }
                    })
                    .show()
            }
        }
    }

    override fun onRefresh(p0: RefreshLayout) {
        toast("正在刷新")
        postDelayed({
            adapter?.clearData()
            this.refreshLayout?.finishRefresh()
        }, 1000)
    }

    override fun onLoadMore(p0: RefreshLayout) {
        toast("没有了")
    }

    override fun onItemClick(recyclerView: RecyclerView?, itemView: View?, position: Int) {
        toast("onItemClick:"+adapter?.getItem(position)?.deviceName)
        ThreadUtils.runOnUiThread {
            /** 点击连接 某一个设备*/
        }
    }

    @SuppressLint("WrongConstant")
    override fun onResume() {
        super.onResume()
        if (Assists.isAccessibilityServiceEnabled()) {
            //开启辅助服务
            btnOpenFZService?.text = getString(R.string.wifi_p2p_opened_assists_service)
        } else {
            //辅助服务已开启
            btnOpenFZService?.text = getString(R.string.wifi_p2p_open_assists_service)
        }
        checkPermissions()
        resumeRecording()
    }

    fun checkPermissions(){
        XXPermissions.with(this)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        toast("获取部分权限成功，但部分权限未正常授予")
                        return
                    }

                }

                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        toast("被永久拒绝授权，请手动授予权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(getAttachActivity(), permissions)
                    } else {
                        toast("获取权限失败")
                    }
                }
            })
    }

    override fun onPause() {
        super.onPause()
        pauseRecording()
    }
    /**
     * 控制消息处理
     */
    @Throws(JSONException::class)
    private fun handleMessage(message: String) {
        val jsonObject = JSONObject(message)
        val type = jsonObject.optString("type")

        //获取屏幕数据
        when (type) {
            "GET_SCREEN" -> {
                val screenWidth = ScreenUtils.getScreenWidth()
                val screenHeight = ScreenUtils.getScreenHeight()
                //响应当前设备宽高
                tcpSender?.sendMessage(GsonUtils.toJson(hashMapOf<String, Any>().apply {
                    put("type", "GET_SCREEN_RESPONSE")
                    put("data", hashMapOf<String, Any>().apply {
                        put("screenWidth", screenWidth)
                        put("screenHeight", screenHeight)
                    })
                    put("orientation", Assists.service?.resources?.configuration?.orientation ?: Configuration.ORIENTATION_PORTRAIT)
                }))

//                lifecycleScope.launch {
//                    intentActivityResultLauncher!!.launch(mMediaProjectionManager!!.createScreenCaptureIntent())
//                }
            }
            //屏幕控制
            "CONTROL" -> {
                val data = jsonObject.optJSONObject("data") ?: return
                //路径数据
                val paths = data.optJSONArray("paths") ?: return
                val path = Path()
                //遍历构建手势路径
                for (i in 0 until paths.length()) {
                    val point = paths.optJSONObject(i)
                    val x = point.optInt("x")
                    val y = point.optInt("y")
                    if (i == 0) {
                        path.moveTo(x.toFloat(), y.toFloat())
                    } else {
                        path.lineTo(x.toFloat(), y.toFloat())
                    }
                }
                //手势执行时长
                val duration = data.optLong("duration")
                //执行控制手势，10为延迟时间
                Assists.gesture(path, 10, duration)
            }

            "BACK" -> {
                //返回
                Assists.back()
            }

            "HOME" -> {
                //回到主页
                Assists.home()
            }
            "TASKS" -> {
                //最近任务
                Assists.tasks()
            }
            "NOTIFICATIONS" -> {
                //通知栏
                Assists.notifications()
            }
        }
    }

    /**
     * 开启无障碍 辅助服务设置
     */
    private fun showSettingService() {
        if (Assists.service != null) return

        MessageDialog.Builder(getApplication()!!.applicationContext)
            .setTitle(R.string.common_permission_alert)
            .setMessage("请开启无障碍->辅助服务,找到本App名字，点击开启")
            .setConfirm("去授权")
            .setCancel("取消")
            .setCancelable(false)
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: BaseDialog?) {
                    Assists.openAccessibilitySetting()
                }
            })
            .show()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getAttachActivity()?.moveTaskToBack(true)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        stopRecording()
        super.onDestroy()
    }

    override fun isStatusBarEnabled(): Boolean {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled()
    }



    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

    fun requestRecordSuccess() {
        isRecord = true
        startRecord()
    }

    fun requestRecordFail() {
        Timber.d("requestRecordFail...")
    }

    private fun startRecord() {
//        val packer: TcpPacker = TcpPacker()
//        mVideoConfiguration = VideoConfiguration.AdvancedBuilder().build()
//        setVideoConfiguration(mVideoConfiguration)
//        setRecordPacker(packer)
//
//        tcpSender = TcpSender(serverIP, Constant.port)
//        tcpSender?.setSenderListener(this)
//        tcpSender?.setVideoParams(mVideoConfiguration)
//        tcpSender?.connect()
//        setRecordSender(tcpSender)
//        startRecording()
    }

    fun setVideoConfiguration(videoConfiguration: VideoConfiguration?) {
        mStreamController?.setVideoConfiguration(videoConfiguration)
    }

    fun startRecording() {
        mStreamController?.start()
    }

    fun stopRecording() {
        mStreamController?.stop()
    }

    fun pauseRecording() {
        mStreamController?.pause()
    }


    fun resumeRecording() {
        mStreamController?.resume()
    }


    fun setRecordPacker(packer: Packer?) {
        mStreamController?.setPacker(packer)
    }

    fun setRecordSender(sender: Sender?) {
        mStreamController?.setSender(sender)
    }

    override fun onConnecting() {
        Timber.d("onConnecting...")
    }

    override fun onConnected() {
        Timber.d("onConnected...")
    }

    override fun onDisConnected() {
        Timber.d("onDisConnected...")
    }

    override fun onPublishFail() {
        Timber.d("onPublishFail...")
    }

    override fun onNetGood() {
    }

    override fun onNetBad() {
    }

    override fun onReceiveMessage(message: String?) {
        Timber.d("message $message")
    }

    override fun shutDown() {

    }

}